import React, { useEffect, useRef, useState } from "react";
import { Table, Row, Col, Input, Form, Button, Switch, Space, Divider, Image, message, Modal, Select, Cascader } from 'antd'
import Prefix from '../../components/prefix'
import { SearchOutlined, PlusOutlined } from '@ant-design/icons';
import * as apis from '../../lib/api'
import * as tool from '../../lib/tool'
import http from '../../lib/http'
import _ from 'lodash'
import Add from './add'
import { handleValue } from '../../components/upload'



const Index = () => {
    const [search, setSearch] = useState({page: 1,page_size: 20})
    const [loading, setLoading] = useState(false)
    const [data, setData] = useState()
    const [seleckeys, setSeleckeys] = useState([])
    const [category, setCategory] = useState([])
    const [orgCategory, setOrgCategory] = useState([])
    const [orgPubCategory, setOrgPubCategory] = useState([])
    
    const [pubCategory, setPubCategory] = useState([])
    const [curPubCategoryId, setCurPubCategoryId] = useState([])
    const [curItem, setCurItem] = useState()
    const [pubModalOpen, setPubModalOpen] = useState()

    const addRef = useRef()

    const loadData = async (s) => {
        try {
            if(s.category_id && s.category_id[0]){
                s.category_id = s.category_id[0]
            }
            if(s.category_id && s.category_id[1]){
                s.second_category_id = s.category_id[1]
            }
            if(s.category_id && s.category_id[2]){
                s.three_category_id = s.category_id[2]
            }
            s.assist = 1
            setData(await http.post(apis.FABRIC_ADMIN_LIST,s))
            setSeleckeys([])
        } catch (error) {
            
        }
    }

    const onSearch = async (values) => {
        let cpSearch = {...search}
        cpSearch.name = values?.name
        cpSearch.category_id = values?.category_id
        cpSearch.page = 1
        cpSearch.status = values?.status
        cpSearch.is_pub = values?.is_pub
        setLoading(true)
        await loadData(cpSearch)
        setLoading(false)
        setSearch(cpSearch)
    }

    const pageSearch = async (page,page_size) => {
        let cpSearch = {...search}
        cpSearch.page_size = page_size
        cpSearch.page = page
        setLoading(true)
        await loadData(cpSearch)
        setLoading(false)
        setSearch(cpSearch)
    }

    const showChange = async (checked,v) => {
        const cpData = _.cloneDeep(data)     
        const index = cpData?.list?.findIndex(m => m.id === v.id)
        if(index !== -1){
            cpData.list[index].status = checked ? 1:2
            setLoading(true)
            try {
                await http.post(apis.FABRIC_SHOW_UPDATE,{id: v.id,status: cpData.list[index].status})
            } catch (error) {
                
            }
            setLoading(false)
            setData(cpData)
        }
    }

    const del = async (ids) => {
        setLoading(true)
        try {
            await http.post(apis.FABRIC_DELETE,{ids})
            message.success("操作成功")
            await loadData(search)
        } catch (error) {
            
        }
        setLoading(false)
    }

    const updatePub = async (param) => {
        setLoading(true)
        try {
            await http.post(apis.FABRIC_PUB_UPDATE,param)
            message.success("操作成功")
            await loadData(search)
        } catch (error) {
            
        }
        setLoading(false)
    }

    const add = () => {
        addRef.current.setIsModalOpen(true)
        addRef.current.resetFields()
        addRef.current.setFieldsValue({})
    }

    const edit = (v) => {
        addRef.current.setIsModalOpen(true)
        addRef.current.resetFields()
        const maps = JSON.parse(v.maps)
        if(v.param){
            var param = JSON.parse(v.param)
        }
        const m = {}
        for(let i=0;i<maps.length;i++){
            m[maps[i].map] = maps[i].url
        }
        const updateData = {
            id: v.id,
            category_id: [v.category_id, v.second_category_id, v.three_category_id], 
            name: v.name, 
            cover: handleValue(v.cover),
            map: handleValue(m["map"]),
            normalMap: handleValue(m["normalMap"]),
            specularMap: handleValue(m["specularMap"] ? m["specularMap"]:""),
            aoMap: handleValue(m["aoMap"] ? m["aoMap"]:""),
            displacementMap: handleValue(m["displacementMap"] ? m["displacementMap"]:""),
            roughnessMap: handleValue(m["roughnessMap"] ? m["roughnessMap"]:""),
            metalnessMap: handleValue(m["metalnessMap"] ? m["metalnessMap"]:""),
            param: param,
            code: v.code,
            element: v.element,
            remark: v.remark
        }
        let new_category_id = []
        for(let i=0;i<updateData.category_id.length;i++){
            if(updateData.category_id[i] !== 0){
                new_category_id.push(updateData.category_id[i])
            }
        }
        if(!param){
            delete updateData.param
        }
        updateData.category_id = new_category_id
        addRef.current.setFieldsValue(updateData)
    }

    const onRefresh = async (isInit) => {
        if(!isInit){
            setLoading(true)
            await loadData(search)
            setLoading(false)
            return
        }
        let cpSearch = {...search}
        cpSearch.page = 1
        setLoading(true)
        await loadData(cpSearch)
        setLoading(false)
        setSearch(cpSearch)
    }

    useEffect(()=>{
        setLoading(true)
        loadData(search).then(r => {
            setLoading(false)
        })

        http.post(apis.FABRIC_CATEGORY_LIST,{is_pub: 2, status: 1, assist: 1}).then(r => {
            setCategory(tool.handleLevelData(r))
            setOrgCategory(r)
        })
        http.post(apis.FABRIC_CATEGORY_LIST,{is_pub: 1, status: 1, assist: 1}).then(r => {
            setPubCategory(tool.handleLevelData(r))
            setOrgPubCategory(r)
        })

        // http.post(apis.FABRIC_PUB_CATEGORY_LIST,{page: 1,page_size: 100,status: 1}).then(r => {
        //     setPubCategory(r?.list)
        // })
        // eslint-disable-next-line
    },[])

    const columns = [
        {
            title: 'ID',
            dataIndex: 'id',
            key: 'id'
        },
        {
            title: '名字',
            dataIndex: 'name',
            key: 'name'
        },
        {
            title: '所属分类',
            dataIndex: 'category_id',
            key: 'category_id',
            render: (v,r) => {
                const cs = [r.category_id,r.second_category_id,r.three_category_id]
                const txt = []
                for(let i=0;i<cs.length;i++){
                    let f = orgCategory.find(s => s.id === cs[i])
                    if(f){
                        txt.push(f.name)
                    }
                }
                return <span>{txt.join()}</span>
            }
        },
        {
            title: '公开分类',
            dataIndex: 'category_id',
            key: 'category_id',
            render: (v,r) => {
                const cs = [r.pub_category_id,r.second_pub_category_id,r.three_pub_category_id]
                const txt = []
                for(let i=0;i<cs.length;i++){
                    let f = orgPubCategory.find(s => s.id === cs[i])
                    if(f){
                        txt.push(f.name)
                    }
                }
                return <span>{txt.join()}</span>
            }
        },
        {
            title: '封面',
            dataIndex: 'cover',
            key: 'cover',
            render: (v) => (
                <Image src={process.env.REACT_APP_OSS_URL+v+"?x-oss-process=image/resize,w_300"} width={60} height={60} fallback="" />
            )
        },
        {
            title: '是否显示',
            dataIndex: 'status',
            key: 'status',
            render: (v,r) => (
                <Switch checked={v === 1} onChange={(e) => showChange(e,r)} />
            )
        },
        {
            title: '可见性',
            dataIndex: 'is_pub',
            key: 'is_pub',
            render: (v,r) => (
                v === 1 ? "公开":"私有"
            )
        },
        {
            title: '创建时间',
            dataIndex: 'created_at',
            key: 'created_at'
        },
        {
            title: '操作',
            dataIndex: 'a',
            key: 'a',
            render: (v,r) => (
                <>
                    <Button loading={loading} type="link" onClick={()=> edit(r)} style={{padding: 0}}>编辑</Button>
                    <Divider type="vertical" />
                    <Button loading={loading} style={{padding: 0}} type="link" onClick={async ()=> {
                        if(r.is_pub === 1){
                            await updatePub({
                                id: r.id,
                                is_pub: 2,
                                pub_category_id: 0,
                                second_pub_category_id: 0,
                                three_pub_category_id: 0
                            })
                            return
                        }
                        setPubModalOpen(true)
                        setCurPubCategoryId([])
                        setCurItem(r)
                    }}>{r.is_pub === 1 ? "取消公开":"公开"}</Button>
                    <Divider type="vertical" />
                    <Button loading={loading} style={{padding: 0}} type="link" danger onClick={()=> {
                         Modal.confirm({
                            title: "提示",
                            content: <p>确定删除吗?</p>,
                            onOk: async () => {
                                await del([r.id])
                            }
                        })
                    }}>删除</Button>
                </>
            )
        }
    ]

    return (
        <div>
            <Modal 
                title="提示"
                open={pubModalOpen}
                onCancel={()=>{
                    setPubModalOpen(false)
                }}
                onOk= {async () => {
                    if(curPubCategoryId.length === 0){
                        message.error("请选择分类")
                        return
                    }
                    await updatePub({
                        id: curItem.id,
                        is_pub: 1,
                        pub_category_id: curPubCategoryId[0] ? curPubCategoryId[0]:0,
                        second_pub_category_id: curPubCategoryId[1] ? curPubCategoryId[1]:0,
                        three_pub_category_id: curPubCategoryId[2] ? curPubCategoryId[2]:0
                    })
                    setPubModalOpen(false)
                }}
            >
                <div>
                    <p>公开后，所有人可见，请选择公开后所属分类：</p>
                    <Cascader style={{width: "100%"}} value={curPubCategoryId} onChange={(v)=> setCurPubCategoryId(v)} allowClear options={pubCategory} placeholder="请选择" />
                </div>
            </Modal>
            <Add category={category} funcs={addRef} onRefresh={onRefresh} />
            <Form onFinish={onSearch}>
                <Row gutter={16}>
                    <Col span={8}>
                        <Form.Item name="name">
                            <Prefix label="名称">
                                <Input allowClear placeholder="请输入名称" />
                            </Prefix>
                        </Form.Item>
                    </Col>
                    <Col span={8}>
                        <Form.Item name="category_id">
                            <Prefix label="所属分类">
                                <Cascader allowClear options={category} placeholder="请选择" />
                            </Prefix>
                        </Form.Item>
                    </Col>
                    <Col span={8}>
                        <Form.Item name="status">
                            <Prefix label="是否禁用">
                                <Select allowClear placeholder="请选择">
                                    <Select.Option value={1}>启用</Select.Option>
                                    <Select.Option value={2}>禁用</Select.Option>
                                </Select>
                            </Prefix>
                        </Form.Item>
                    </Col>
                </Row>
                <Row gutter={16}>
                    <Col span={8}>
                        <Form.Item name="is_pub">
                            <Prefix label="是否公开">
                                <Select allowClear placeholder="请选择">
                                    <Select.Option value={1}>公开</Select.Option>
                                    <Select.Option value={2}>私有</Select.Option>
                                </Select>
                            </Prefix>
                        </Form.Item>
                    </Col>
                    <Col span={8}>
                        <Form.Item>
                            <Space>
                                <Button loading={loading} type="primary" htmlType="submit" icon={<SearchOutlined />}>查询</Button>
                                <Button onClick={add} loading={loading} ghost type="primary" icon={<PlusOutlined />}>新增</Button>
                            </Space>
                        </Form.Item>
                    </Col>
                </Row>
            </Form>
            <Space>
                <span>已选 {seleckeys?.length} 条</span>
                <Button danger disabled={seleckeys?.length === 0} onClick={() => {
                    Modal.confirm({
                        title: "提示",
                        content: <p>确定删除 <span style={{color: 'red'}}>{seleckeys?.length}条</span> 数据吗?</p>,
                        onOk: async () => {
                            await del(seleckeys)
                        }
                    })
                }}>批量删除</Button>
            </Space>
            <div style={{height: 12}}></div>
            <Table 
                rowKey={'id'}
                dataSource={data?.list || []} 
                loading={loading} 
                columns={columns}
                pagination={{
                    showQuickJumper: true,
                    showSizeChanger: true,
                    onChange: pageSearch,
                    total: data?.total,
                    current: data?.page,
                    pageSize: data?.page_size
                }}
                scroll={{
                    y: 'calc(100vh - 510px)'
                }}
                rowSelection={{
                    onChange: (keys) => {
                        setSeleckeys(keys)
                    },
                    selectedRowKeys: seleckeys
                }}
            />
        </div>
    )
}

export default Index